/*
 * @Author: 汪军 624473119@qq.com
 * @Date: 2023-10-22 14:16:14
 * @LastEditors: 汪军 624473119@qq.com
 * @LastEditTime: 2023-10-22 16:31:07
 * @FilePath: \app-formwork\src\config\index.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { BASE_API } from "@/config";

let requestTree = {};

function message(data) {
  const { code, msg } = data;
  switch (code) {
    case 0:
      uni.showToast({
        icon: "error",
        title: msg,
        duration: 800,
      });
      break;
    default:
      uni.showToast({
        icon: "none",
        title: msg,
        duration: 800,
      });
      break;
  }
}

// 终止所有发送中的请求
function abortRequest() {
  for (const name in requestTree) requestTree[name].abort();
  requestTree = {};
}

// 删除用户登录信息
const removeUserInfo = () => {
  uni.removeStorageSync("userInfo");
};

function baseRequest(method, url, data = {}) {
  // 获取用户登录信息
  // const userInfo = JSON.parse(uni.getStorageSync("userInfo"));
  // console.log('数据',JSON.parse(uni.getStorageSync("userInfo")));

  const token = uni.getStorageSync('token')

  return new Promise((resolve) => {
    const header = {
      "content-type": "application/json; charset=utf-8",
    };
    // header.token = userInfo?.token;
    header.token = token
    let responseData;
    requestTree[url] = uni.request({
      url: BASE_API + url,
      method,
      timeout: 20000,
      header,
      data,
      success: (res) => {
        if (res.statusCode >= 200 && res.statusCode < 400) {
          // 正常返回
          if (res.data.code === 1||res.data.code==0 ) {
            responseData = res.data;
          } else {
            // message(res.data);
          }
        } else if (res.data.code === 401) {
          abortRequest();
          removeUserInfo();
          uni.showToast({ title:'请登录后操作', icon: "none" });
          uni.reLaunch({
            url: "/pages/login/index",
          });
        } else {
          // message(res.data);
        }
      },
      fail: (res) => {
        // message(res.data);
      },
      complete: () => {
        delete requestTree[url];
        // 正常返回
        resolve(responseData);
        if (!responseData) return;
      },
    });
  });
}

const request = {
  get: (api, params) => baseRequest("GET", api, { ...params }),
  post: (api, params) => baseRequest("POST", api, { ...params }),
  delete: (api, params) => baseRequest("DELETE", api, { ...params }),
};

export default request;
